﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;


namespace FillServiceForm
{
    public partial class Form1 : Form
    {
        
        private Thread piThread = null;        
        private ClientListener listener = null;

        public Form1()
        {
            InitializeComponent();

            listener = new ClientListener(this);
        }        

        private void button1_Click(object sender, EventArgs e)
        {
            if (piThread == null && !listener.isStart )
            {
                piThread = new Thread(new ThreadStart(listener.startListening));
                piThread.Start();                
                txtMessage.Text += "Start Socket. Listening ...\r\n";
            }
            else
                MessageBox.Show("Threading already started");
            
        }

        private void stopButton_Click(object sender, EventArgs e)
        {
            if (piThread != null && piThread.IsAlive)
            {
                txtMessage.Text += "Stop Listening ...\r\n";
                listener.stopListening();                
                piThread.Abort("Aborting the thread ... ");
                piThread.Join();
                piThread = null;
                
            }
        }

        public delegate void AddMessageDelegate(String text,bool messageBox);

        public void addMessage(String str,bool messageBox)
        {
            if (this.txtMessage.InvokeRequired)
            {
                // This is a worker thread so delegate the task.
                this.txtMessage.Invoke(new AddMessageDelegate(this.addMessage), new object[]{str,messageBox});
            }
            else
            {
                if (!messageBox)
                    txtMessage.Text += str + " \r\n";
                else
                    MessageBox.Show(str);
            }
        }
    }
}
